package cipher

import (
	"bytes"
	"crypto/aes"
	"crypto/cipher"
	"crypto/sha1"
	"encoding/base64"
	"errors"
	"fmt"
	"net/url"
)

const (
	// defaultAesKey 默认的aes key 32位
	defaultAesKey = "759e7e0e85e2e927382b0e1259637d41"

	// defaultAesIv 默认的aes iv 16位
	defaultAesIv = "bdc3ad6584ca3b4a"
)

type (
	aesCipher struct {
		key   []byte
		iv    []byte
		block cipher.Block
	}

	IAesCipher interface {
		EncryptAesBase64(in []byte) (string, error)
		DecryptAesBase64(b string) ([]byte, error)
	}

	Option func(*aesCipher)
)

// NewAesCipher 创建一个新的AesCipher
func NewAesCipher(opts ...Option) (IAesCipher, error) {
	aesExcept := aesCipher{
		key: []byte(defaultAesKey),
		iv:  []byte(defaultAesIv),
	}

	for _, o := range opts {
		o(&aesExcept)
	}

	var err error

	aesExcept.block, err = aes.NewCipher(aesExcept.key)
	if err != nil {
		return nil, err
	}
	return &aesExcept, nil
}

// WithAesKey 设置key
func WithAesKey(key []byte) Option {
	return func(a *aesCipher) {
		if len(key) == 0 {
			return
		}
		a.key = key
	}
}

// WithAesIv 设置iv
func WithAesIv(iv []byte) Option {
	return func(a *aesCipher) {
		if len(iv) == 0 {
			return
		}
		a.iv = iv
	}
}

// EncryptAesBase64 加密
func (a *aesCipher) EncryptAesBase64(in []byte) (string, error) {
	origData := in
	origData = pkCS5Padding(origData, a.block.BlockSize())
	crypt := make([]byte, len(origData))
	// 根据CryptBlocks方法的说明，如下方式初始化crypt也可以
	bm := cipher.NewCBCEncrypter(a.block, a.iv)
	bm.CryptBlocks(crypt, origData)
	var b = base64.StdEncoding.EncodeToString(crypt)
	return b, nil
}

// DecryptAesBase64 解密
func (a *aesCipher) DecryptAesBase64(b string) ([]byte, error) {
	crypt, err := base64.StdEncoding.DecodeString(b)
	if err != nil {
		return []byte{}, err
	}
	origData := make([]byte, len(crypt))
	bm := cipher.NewCBCDecrypter(a.block, a.iv)
	bm.CryptBlocks(origData, crypt)
	origData = pkCS5UnPadding(origData)
	return origData, nil
}

func pkCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padText...)
}

func pkCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	// 去掉最后一个字节 unPadding 次
	unPadding := int(origData[length-1])
	return origData[:(length - unPadding)]
}

func Encrypt(encryptContent string, encryptKey string) ([]byte, error) {
	if encryptContent == "" || encryptKey == "" {
		return nil, errors.New("encryptContent or encryptKey can't be empty")
	}

	key := []byte(encryptKey)
	content := []byte(encryptContent)

	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}

	blockSize := block.BlockSize()
	plaintext := pkCS5Padding(content, blockSize)

	ciphertext := make([]byte, len(plaintext))
	for bs, be := 0, blockSize; bs < len(plaintext); bs, be = bs+blockSize, be+blockSize {
		block.Encrypt(ciphertext[bs:be], plaintext[bs:be])
	}

	return ciphertext, nil
}

func Decrypt(decryptContent []byte, decryptKey string) ([]byte, error) {
	if len(decryptContent) == 0 || decryptKey == "" {
		return nil, errors.New("decryptContent or decryptKey can't be empty")
	}

	key := []byte(decryptKey)
	ciphertext := decryptContent
	block, err := aes.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockSize := block.BlockSize()
	plaintext := make([]byte, len(ciphertext))

	for bs, be := 0, blockSize; bs < len(ciphertext); bs, be = bs+blockSize, be+blockSize {
		block.Decrypt(plaintext[bs:be], ciphertext[bs:be])
	}

	return pkCS5UnPadding(plaintext), nil
}

func EncryptWithURLEncoder(encryptContent string, encryptKey string) (string, error) {
	ciphertext, err := Encrypt(encryptContent, encryptKey)
	if err != nil {
		return "", err
	}

	encoded := base64.URLEncoding.EncodeToString(ciphertext)
	encrypted := url.QueryEscape(encoded)

	return encrypted, nil
}

func AesEncryptECB(origData []byte, key []byte) (encrypted []byte) {
	key, _ = aesSha1Padding(key, 128)

	newCipher, _ := aes.NewCipher(generateKey(key))
	length := (len(origData) + aes.BlockSize) / aes.BlockSize
	plain := make([]byte, length*aes.BlockSize)
	copy(plain, origData)
	pad := byte(len(plain) - len(origData))
	for i := len(origData); i < len(plain); i++ {
		plain[i] = pad
	}
	encrypted = make([]byte, len(plain))
	// 分组分块加密
	for bs, be := 0, newCipher.BlockSize(); bs <= len(origData); bs, be = bs+newCipher.BlockSize(), be+newCipher.BlockSize() {
		newCipher.Encrypt(encrypted[bs:be], plain[bs:be])
	}

	return encrypted
}

func AesDecryptECB(encrypted []byte, key []byte) ([]byte, error) {
	key, err := aesSha1Padding(key, 128)
	if err != nil {
		return nil, err
	}

	block, _ := aes.NewCipher(generateKey(key))
	decrypted := make([]byte, len(encrypted))

	for bs, be := 0, block.BlockSize(); bs < len(encrypted); bs, be = bs+block.BlockSize(), be+block.BlockSize() {
		block.Decrypt(decrypted[bs:be], encrypted[bs:be])
	}

	trim := 0
	if len(decrypted) > 0 {
		trim = len(decrypted) - int(decrypted[len(decrypted)-1])
	}

	return decrypted[:trim], nil
}

func aesSha1Padding(keyBytes []byte, encryptLength int) ([]byte, error) {
	hashes := Sha1(Sha1(keyBytes))
	maxLen := len(hashes)
	realLen := encryptLength / 8
	if realLen > maxLen {
		return nil, fmt.Errorf("invalid length")
	}
	return hashes[0:realLen], nil
}

func Sha1(data []byte) []byte {
	h := sha1.New()
	h.Write(data)
	return h.Sum(nil)
}

func generateKey(key []byte) (genKey []byte) {
	genKey = make([]byte, 16)
	copy(genKey, key)
	for i := 16; i < len(key); {
		for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
			genKey[j] ^= key[i]
		}
	}
	return genKey
}
